package com.adgroup.doremon_ad;

import io.vov.vitamio.LibsChecker;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import model.User;
import model.Video;
import model.VideoID;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import quick.action.ActionItem;
import quick.action.QuickAction;
import util.Config;
import util.CustomDialogClass;
import util.NetworkUtil;
import util.Utility;
import vn.adflex.ads.AdFlex;
import vn.adflex.ads.Ads;
import vn.adflex.ads.AdsListener;
import vn.adflex.ads.AdsRequest;
import vn.adflex.ads.ErrorCode;
import vn.adflex.ads.InterstitialAds;
import adapter.AdapterVideo;
import adapter.AdapterVideo.IOnClickItemVideo;
import adapter.JsonParse;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.androidquery.AQuery;
import com.facebook.FacebookException;
import com.facebook.UiLifecycleHelper;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;
import com.facebook.widget.WebDialog;
import com.facebook.widget.WebDialog.OnCompleteListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

import com.slidingmenu.lib.SlidingMenu;

import database.Database;

public class MainActivity extends SherlockFragmentActivity implements Menufragment.MenuClickInterFace,IOnClickItemVideo {
	public static boolean loadmore = true;
	String urlllk; 
	SlidingMenu menu; 
	//String idchannelllk;
	int max_count_video = 10;
	ListView lvvideo;  
	AdapterVideo adapter; 
	View footer; 
	ImageView adv;
	ImageView nodata;
	String urlvideo;
	TextView count;
	ProgressBar waiting;
	Handler handler = new Handler();
	private View header;
	private ActionBar mActionBar;
	private ImageView ivLogin, ivHome;
	public static ArrayList<VideoID> video = new ArrayList<VideoID>();
	public static int n = 0;
	public static String ID;
	private int mSelectedRow = 0;
	QuickAction mQuickAction;
	User u;
	AsynSearch asynSearch;
	@SuppressWarnings("deprecation")
	private AsyncFacebookRunner mAsyncRunner;
	private static final String[] PERMS = new String[] { "read_stream" ,"offline_access"};
	
	@SuppressWarnings("deprecation")
	private Facebook facebook;
	private UiLifecycleHelper uiHelper;
	public static HashMap<String, String>hmUrl = new HashMap<String, String>(); 
	
	interface IShareToFacebook{
		void onShareToFacebook();
	}
	
	
	
	
	@SuppressWarnings("deprecation")
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		 AdView mAdView = (AdView) this.findViewById(R.id.adView);
		    AdRequest adRequest = new AdRequest.Builder().build();
		    mAdView.loadAd(adRequest);
		
		 //AdFlexBannerAds adFlexBannerAds = new AdFlexBannerAds(MainActivity.this, true, getResources().getString(R.string.banner_ad_unit_id));

		// Create an ad.
		if(getIntent().getStringExtra("exit")!=null && getIntent().getStringExtra("exit").equalsIgnoreCase("exit")){
			finish();
		}
 
		facebook = new Facebook(getResources().getString(R.string.facebook_app_id));
		mAsyncRunner = new AsyncFacebookRunner(facebook);
		/*uiHelper = new UiLifecycleHelper(this, new StatusCallback() {
			
			@Override
			public void call(Session session, SessionState state, Exception exception) {
				// TODO Auto-generated method stub
				
			}
		});
	    uiHelper.onCreate(savedInstanceState);*/
	    
		//get action bar
		mActionBar = getSupportActionBar(); 
		mActionBar.setDisplayShowHomeEnabled(false);
		mActionBar.setDisplayShowTitleEnabled(false);
		
		View custom = LayoutInflater.from(MainActivity.this).inflate(R.layout.customactionbar, null);
		ivLogin = (ImageView) custom.findViewById(R.id.imageViewLoginactionbar);
		ivHome = (ImageView) custom.findViewById(R.id.menuViewButtonLogoactionbar);
		
		mActionBar.setCustomView(custom);
		mActionBar.setDisplayShowCustomEnabled(true);
		 mActionBar.setLogo(new ColorDrawable(Color.TRANSPARENT));
		 
		menu = new SlidingMenu(this);
		menu.setMode(SlidingMenu.LEFT);
		menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
		menu.setShadowWidthRes(R.dimen.shadow_width);
		menu.setShadowDrawable(R.drawable.shadow);
		menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		menu.setFadeDegree(0.25f);
		menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
		menu.setMenu(R.layout.menu);
		menu.setSlidingEnabled(true);
		
		//home
		ivHome.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				menu.toggle();
			}
		});
		//login
		ivLogin.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				User u = new Database(MainActivity.this).getUser();
				if(u!=null){ 
					Intent i = new Intent(MainActivity.this, MyProfileActivity.class);
					startActivityForResult(i, Config.requestMyProfile);
				} 
				else{
					Intent i = new Intent(MainActivity.this, LoginActivity.class);
					startActivityForResult(i, Config.requestLogin);
				}
			}
		}); 
		
		urlvideo = getResources().getString(R.string.urlvideo);
		View actionbar = getLayoutInflater().inflate(R.layout.actionbar, null);
		TextView title = (TextView) actionbar.findViewById(R.id.textView1);
		waiting = (ProgressBar) findViewById(R.id.progressBarWaitingMain);
		count=(TextView)actionbar.findViewById(R.id.textViewCount);
		title.setText(getResources().getString(R.string.title_app));
		title.setTextColor(Color.parseColor("#0099CC"));		
		footer = getLayoutInflater().inflate(R.layout.footervideo, null);
		footer.setVisibility(View.INVISIBLE);
		footer.setEnabled(false);
		
		lvvideo = (ListView) findViewById(R.id.listViewVideo);
		nodata = (ImageView) findViewById(R.id.imageViewnodata);
		lvvideo.addFooterView(footer);   
		   
		
		lvvideo.setOnScrollListener(new EndlessScrollListener());

		adapter = new AdapterVideo(MainActivity.this,new ArrayList<Video>()); 
		lvvideo.setAdapter(adapter);
		
		lvvideo.setOnItemClickListener(new OnItemClickListener() {

			@Override 
			public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {  
				// TODO Auto-generated method stub
				try {    
					Video v = (Video) adapter.getItem(pos);
					if(v!=null){
						String url = v.getPlayer_mobile(); 
						if(url.length()<=6){
							url = v.getPlayer_default();
							url = url.substring(url.indexOf("v=")+2, url.lastIndexOf("&feature"));
						}
						else{
							url = url.substring(url.lastIndexOf("v=")+2);
						}
						if(hmUrl.containsKey(url) ){
							Intent intent = new Intent(MainActivity.this, VideoViewBuffer.class);
							intent.putExtra("ID",  hmUrl.get(url));
							intent.putExtra("videoID",  url);
							intent.putExtra("IDInt",  v.getId()+"");
							intent.putExtra("title", v.getTitle());
							intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
							startActivity(intent);
							overridePendingTransition(R.anim.in, R.anim.out);
						}
						else{
							new AsynGetLinkYouTube().execute(new String[]{url, v.getId()+"",v.getTitle()});
						}
						
					} 
				} catch (Exception e) {
				} 
			} 
		});
		prepareshare();
		SharedPreferences share = getSharedPreferences("sharefilmllk",
				MODE_PRIVATE);
		checkNet();
		if (hasNetwork) {
		/*	if(asynSearch==null){
				page = 1;
				ID = Config.mostlatest;
				asynSearch = new AsynSearch(ID);
				asynSearch.execute();
			}*/
			checkversion();
		} else {
			showMSG();
		} 
		
		//quick action
		 ActionItem addItem 		= new ActionItem(Config.ID_LIKE, getResources().getString(R.string.Likes), getResources().getDrawable(R.drawable.like));
			ActionItem acceptItem 	= new ActionItem(Config.ID_COMMENT, getResources().getString(R.string.comment), getResources().getDrawable(R.drawable.comment));
			ActionItem shareItem 	= new ActionItem(Config.ID_SHARE, getResources().getString(R.string.share), getResources().getDrawable(R.drawable.share_fb));
	         
			mQuickAction 	= new QuickAction(this);
			
			mQuickAction.addActionItem(addItem);
			mQuickAction.addActionItem(acceptItem);
			mQuickAction.addActionItem(shareItem);
			//setup the action item click listener
			mQuickAction.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
				@Override
				public void onItemClick(QuickAction quickAction, int pos, int actionId) {
					ActionItem actionItem = quickAction.getActionItem(pos);
					
					if (actionId == Config.ID_LIKE) { //Add item selected
						//Toast.makeText(getApplicationContext(), "Add item selected on row " + mSelectedRow, Toast.LENGTH_SHORT).show();
						User user = new Database(getApplicationContext()).getUser();
						if(user==null){							
								new AlertDialog.Builder(MainActivity.this)
								.setTitle(getResources().getString(R.string.buttonlogin))
								.setMessage(getResources().getString(R.string.messagelogintoliked))
								.setNegativeButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
									
									@Override
									public void onClick(DialogInterface dialog, int which) {
										Intent i = new Intent(MainActivity.this, LoginActivity.class);
										startActivityForResult(i, Config.LIKE_TO_LOGIN);
									}
								})
								.setPositiveButton(MainActivity.this.getResources().getString(R.string.cancel),
										new DialogInterface.OnClickListener() {
											public void onClick(DialogInterface dialog,
													int which) {
											}
								}).show();
							
						}else{						
							likeVideo();					
						}
					}
					else if (actionId == Config.ID_COMMENT) { //Add item selected
						//Toast.makeText(getApplicationContext(), "Add item selected on row " + mSelectedRow, Toast.LENGTH_SHORT).show();
						Intent i = new Intent(getApplicationContext(), CommentActivity.class);
						Video v = (Video) adapter.getItem(mSelectedRow);
						i.putExtra("videoID", v.getVideoID()+"");
						i.putExtra("imageID", v.getLink());
						i.putExtra("ID", v.getId()+"");
						i.putExtra("title", v.getTitle());
						i.putExtra("player_default", v.getPlayer_default());
						i.putExtra("player_mobile", v.getPlayer_mobile());
						i.putExtra("desc", "Time: " + v.getDuration()+" - "+v.getViews()+" "+getResources().getString(R.string.views)+", "+v.getLikes()+" "+getResources().getString(R.string.likes));
						startActivity(i);
					}
					else if (actionId == Config.ID_SHARE) { //Add item selected
						ivHome.setTag("fb");
						User u = new Database(MainActivity.this).getUser();
						v = (Video) adapter.getItem(mSelectedRow);
						//if(u!=null && u.getType().equalsIgnoreCase(Config.typeFacebook))
						{				
							SharedPreferences share = getSharedPreferences("sharefilmllk",
								      MODE_PRIVATE);
								    SharedPreferences.Editor editor = share.edit();
								   
							//SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(DetailChartActivity.this);
							facebook.setAccessToken(share.getString("access", "0"));
							long expied = share.getLong("access_expires", 0);
							facebook.setAccessExpires(expied);
							 
							if(facebook.getSession()!=null){ 
								
								if(v!=null){
								AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
								alert.setTitle(v.getTitle());
								alert.setMessage(getResources().getString(R.string.shareinfordwithfacebook)+" "+share.getString("username", ""));
								alert.setNeutralButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
									
									@Override
									public void onClick(DialogInterface dialog, int which) {
										publishFeedDialog(null);
									}
								});
								alert.setPositiveButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
									
									@Override
									public void onClick(DialogInterface dialog, int which) {
									}
								});
								alert.setNegativeButton(getResources().getString(R.string.another_account_fb), new DialogInterface.OnClickListener() {
									
									@Override
									public void onClick(DialogInterface dialog, int which) {
										loginFacebook();
									}
								});
								alert.show();	
								}
							}
							else{
								loginFacebook();
							}
						}
						/*else{
							loginFacebook();
						}*/ 
					}
				} 
			});
			
			//setup on dismiss listener, set the icon back to normal
			mQuickAction.setOnDismissListener(new PopupWindow.OnDismissListener() {			
				@Override
				public void onDismiss() {
					adapter.resetButtonDetail();
				}
			});
			//app start
			/*handler.post(new Runnable() {
				
				@Override
				public void run() {
					StartAppAd.init(MainActivity.this, Config.devIDStartApp, Config.appIDStartApp); 
					StartAppSearch.init(MainActivity.this, Config.devIDStartApp, Config.appIDStartApp);
					StartAppSearch.showSearchBox(MainActivity.this); 
				}
			});*/
			if (!LibsChecker.checkVitamioLibs(this))
				return;
	}
	
	
		class AsynGetLinkYouTube extends AsyncTask<String, Void, String>
		{
			String videoID;
			String ID;
			String title;
			
			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();			
				progress = ProgressDialog.show(MainActivity.this, "",
						getResources().getString(R.string.loading), true);	
			}
			@Override
			protected String doInBackground(String... params) {
				this.videoID = params[0];
				this.ID = params[1];
				this.title = params[2];
				return JsonParse.getInstance().getVideoLink(getApplicationContext(), params[0]);
			}
			@Override
			protected void onPostExecute(String result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				progress.dismiss();
				try {
					JSONObject json = new JSONObject(result);
						String url = json.getString(Config.result);
						  
						if(url.equalsIgnoreCase("&&signature=")){
							new AsynRemoveVideo().execute(new String[]{this.ID});
							Utility.ShowAlert(MainActivity.this, getResources().getString(R.string.error), getResources().getString(R.string.error_canot_play));
							adapter.removeVideo(this.ID);
						}
						else{
							hmUrl.put(this.videoID, url);
							Intent intent = new Intent(MainActivity.this, VideoViewBuffer.class);
							intent.putExtra("ID",  url);
							intent.putExtra("videoID",  this.videoID);
							intent.putExtra("IDInt",  this.ID);
							intent.putExtra("title",  this.title);
							intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
							startActivity(intent);
							overridePendingTransition(R.anim.in, R.anim.out);
						}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	
	class AsynRemoveVideo extends AsyncTask<String, Void, Void>
	{

		@Override
		protected Void doInBackground(String... params) {
			JsonParse.getInstance().removeVideo(getApplicationContext(), params[0]);
			return null;
		}
		
	}
	//private StartAppAd startAppAd = new StartAppAd(this); 
	Video v;
	@SuppressWarnings("deprecation") 
	private void loginFacebook() {
		facebook = new Facebook(getResources().getString(R.string.facebook_app_id));
        mAsyncRunner = new AsyncFacebookRunner(facebook);
        facebook.authorize(MainActivity.this, PERMS, new LoginDialogListener());		
	}
	private class LoginDialogListener implements DialogListener {
		 
        @SuppressWarnings("deprecation")
		@Override
        public void onComplete(Bundle values) {  
        	if(ivHome.getTag().toString().equalsIgnoreCase("fb")){
        		ivHome.setTag("nfb");
                mAsyncRunner.request("me", new IDRequestListener());
        	}
        }

        @Override
        public void onFacebookError(FacebookError e) {
        }

        @Override
        public void onError(DialogError e) {
        }

        @Override
        public void onCancel() {
        }
}
	private class IDRequestListener implements RequestListener {

        @Override
        public void onComplete(String response, Object state) {
                try {
                        
                        JSONObject json = Util.parseJson(response);

                        final String id = json.getString("id");
                        final String name = json.getString("name");
                        String access = facebook.getSession().getAccessToken();
						Date d = facebook.getSession().getExpirationDate();
						long milliseconds = d.getTime();
						SharedPreferences share = getSharedPreferences(
								"sharefilmllk", MODE_PRIVATE);
						SharedPreferences.Editor editor = share
								.edit();

						editor.putLong("access_expires",
								milliseconds);
						editor.putString("access", access);

						String email = json.getString("email");
						String birthday = "2012-12-12";//json.getString("birthday");
						final String nickname = json.getString("name");
						String username = json.getString("username");
						editor.putString("username", nickname);
						editor.commit();
						String gender = json.getString("gender");
						if(gender.toLowerCase().equalsIgnoreCase("male")){
							gender = "1";
						}
						else if(gender.toLowerCase().equalsIgnoreCase("female")){
							gender = "0";
						}
						String avatar = json.getString("id");
						avatar = "http://graph.facebook.com/"+avatar+"/picture";
						runOnUiThread(new Runnable() {
							public void run() {
								AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
								alert.setTitle(getResources().getString(R.string.welcomeuser1)+" "+nickname);
								alert.setMessage(getResources().getString(R.string.share_facebook_alert));
								alert.setNeutralButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
									
									@Override
									public void onClick(DialogInterface dialog, int which) {
										publishFeedDialog(null);
									}
								});
								alert.setPositiveButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
									
									@Override
									public void onClick(DialogInterface dialog, int which) {
									}
								});
								
								alert.show();
							}
						});
						//String[] params = new String[] {email,username,birthday,nickname,gender,avatar,Config.typeFacebook,"1","gcmid"};//1: facebook
					//	new AsyntaskLoginWithSocial().execute(params);
							
                } catch (JSONException e) {
                      
                } catch (FacebookError e) {
                      
                }
        }

        @Override
        public void onIOException(IOException e, Object state) {
                
        }

        @Override
        public void onFileNotFoundException(FileNotFoundException e,
                        Object state) {
               
        }

        @Override
        public void onMalformedURLException(MalformedURLException e,
                        Object state) {
                
        }

        @Override
        public void onFacebookError(FacebookError e, Object state) {
                
        }

}
	private void publishFeedDialog(Object object) {
		Bundle params = new Bundle();
		String url1 = getResources().getString(R.string.urldownloadapp);
		url1 = url1.replace(" ", "%20");
	    params.putString("name", v.getTitle());
	    params.putString("caption", v.getTitle()); 
	    params.putString("description", "Time: " + v.getDuration()+" - "+v.getViews()+" "+getResources().getString(R.string.views)+", "+v.getLikes()+" "+getResources().getString(R.string.likes));  
	    params.putString("link", v.getPlayer_default());
	   // params.putString("link", url);
	    Log.d("log",url1);
	    params.putString("picture", v.getLink()); 
	    
	    @SuppressWarnings("deprecation")
		WebDialog feedDialog = (
	        new WebDialog.FeedDialogBuilder(MainActivity.this,
	        		facebook.getSession(), 
	            params))
	        .setOnCompleteListener(new OnCompleteListener() {
 
	            @Override
	            public void onComplete(Bundle values,
	                FacebookException error) {
	                if (error == null) {
	                    // When the story is posted, echo the success
	                    // and the post Id.
	                    final String postId = values.getString("post_id");
	                    if (postId != null) {
	                        Toast.makeText(MainActivity.this,
	                        		v.getTitle() +" is shared",
	                            Toast.LENGTH_SHORT).show();
	                    }	                    
	                }	                
	            }
	        })
	        .build();
	    feedDialog.show();
	} 
	@SuppressWarnings("deprecation")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		facebook.authorizeCallback(requestCode, resultCode, data);
		/*uiHelper.onActivityResult(requestCode, resultCode, data, new FacebookDialog.Callback() {
	        @Override
	        public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) {
	            Log.e("Activity", String.format("Error: %s", error.toString()));
	        }

	        @Override
	        public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
	            Log.i("Activity", "Success!");
	        }
	    });*/
		if(requestCode==Config.requestLogin && resultCode==RESULT_OK){//register then login			
			Toast.makeText(MainActivity.this, getResources().getString(R.string.welcomeuser1)+" "+data.getStringExtra("result")+" "+getResources().getString(R.string.welcomeuser2), Toast.LENGTH_LONG).show();
			UpdateAvatar();
		}
		if(requestCode==Config.requestMyProfile && resultCode==RESULT_OK){//register then login
			//ivLogin.setImageResource(R.drawable.login_select);
			try { 
				if(data.getStringExtra("logout").equalsIgnoreCase("ok")){
					ivLogin.setImageResource(R.drawable.bglogin_logout);
				}
			} catch (Exception e) { 
				// TODO: handle exception
			}
			Toast.makeText(MainActivity.this, data.getStringExtra("result")+" "+getResources().getString(R.string.myprofilelogoutreturn), Toast.LENGTH_LONG).show();
		}
		if(requestCode==Config.LIKE_TO_LOGIN && resultCode==RESULT_OK){//register then login
			likeVideo();
		}
	}
	
	private void likeVideo(){
		String[] a = {((Video)adapter.getItem(mSelectedRow)).getId()+"","1"};
		new AsynLike().execute(a);
		
		progress = ProgressDialog.show(MainActivity.this, "",
				getResources().getString(R.string.sending), true);
		handler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				if(progress.isShowing()){
					progress.dismiss();
				}
			}
		}, 1500);
	}
	 
	private void UpdateAvatar(){
		u = new Database(getApplicationContext()).getUser();
		if(u!=null){
			if(u.getLogo()!=null && u.getLogo().length()>=6){
				AQuery aq = new AQuery(getApplicationContext());
				Bitmap placeholder = aq.getCachedImage(R.drawable.imageload);
				aq.id(ivLogin).image(u.getLogo(), true, true,
						0, 0, placeholder, AQuery.FADE_IN_NETWORK, 1f);
			}
			else{
				ivLogin.setImageResource(R.drawable.social_person_in);
			}
		}
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		UpdateAvatar();
	//	uiHelper.onResume();
		super.onResume(); 
		//startAppAd.onResume(); 
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
	    super.onSaveInstanceState(outState);
	    //uiHelper.onSaveInstanceState(outState);
	}
	public void prepareshare() {
		SharedPreferences share = getSharedPreferences("sharefilmllk",
				MODE_PRIVATE);
		SharedPreferences.Editor editor = share.edit();
		if (!share.contains("checkbox")) {
			editor.putBoolean("checkbox", false);
			editor.putBoolean("require", false);
			editor.putString("version", getVersionName());
			editor.commit();
		}
	}

	public String getApplicationName() {
		PackageManager lPackageManager = getPackageManager();
		ApplicationInfo lApplicationInfo = null;
		try {
			lApplicationInfo = lPackageManager.getApplicationInfo(
					getApplicationInfo().packageName, 0);
		} catch (final NameNotFoundException e) {
		}
		String title = (String) (lApplicationInfo != null ? lPackageManager
				.getApplicationLabel(lApplicationInfo) : "Unknown");
		return title;
	}

	public String getVersionName() {
		String versionName = "0.0";
		try {
			versionName = getPackageManager().getPackageInfo(getPackageName(),
					0).versionName;
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return versionName;
	}

	public void checkversion() {
		String commandvs = getResources().getString(R.string.commandvs);
		String appname = getResources().getString(R.string.appname);
		String urljsonvs = getResources().getString(R.string.urljsonvs);
		Log.d("logTage", urljsonvs + ":" + commandvs + ":" + appname);
		new checkversion(commandvs, urljsonvs, appname, nodata).execute();
	}

	public class checkversion extends AsyncTask<Void, Void, Boolean> {
		public checkversion(String command, String urljson, String appname,
				ImageView nodata) {
			this.urljson = urljson;
			this.command = command;
			this.appname = appname;
			this.nodata = nodata;
		}

		public boolean update(String version) {
			boolean update = false;
			try {
				String versionName = getVersionName();
				float oldversion = Float.parseFloat(versionName);
				float newversion = Float.parseFloat(version);
				if (newversion > oldversion) {
					update = true;
				} else {
					update = false;
				}

			} catch (Exception e) {
				update = false;
			}
			return update;
		}

		ImageView nodata;
		public String urljson;
		public String command;
		String TAG_RESULT = "result";
		String TAG_VERSION = "version";
		String TAG_REQUIRE = "require";
		String appname;
		List<HashMap<String, String>> versions = new ArrayList<HashMap<String, String>>();

		public void checkvs(List<HashMap<String, String>> versions) {
			try {
				boolean update = update(versions.get(0).get("version"));
				String require = versions.get(0).get("require");
				if (update) {
					SharedPreferences share = getSharedPreferences(
							"sharefilmllk", MODE_PRIVATE);
					SharedPreferences.Editor edit = share.edit();
					edit.putString("version", versions.get(0).get("version"));
					if (require.equals("require")) {
						edit.putBoolean("require", true);
					} else {
						edit.putBoolean("require", false);
					}
					edit.commit();
				}

				SharedPreferences share = getSharedPreferences("sharefilmllk",
						MODE_PRIVATE);
				SharedPreferences.Editor editor = share.edit();
				boolean show = share.getBoolean("checkbox", false);
				if (update && !show && require.equals("notrequire")) {
					final Dialog dialog = new CustomDialogClass(
							MainActivity.this).createCustomDialog(
							R.layout.dialog_version_check, MainActivity.this,
							getResources().getString(R.string.infor), getResources().getString(R.string.new_update), false);

					dialog.show();
					Log.d("logTag", "noo máº¡ng");
					final CheckBox checkshow = (CheckBox) dialog
							.findViewById(R.id.checkBoxCapnhat);
					checkshow.setText(getResources().getString(R.string.dont_display));
					Button buttonCapnhat = (Button) dialog
							.findViewById(R.id.buttonCapnhat);
					Button buttonDesau = (Button) dialog
							.findViewById(R.id.buttonDesau);
					buttonCapnhat
							.setOnClickListener(new View.OnClickListener() {

								@Override
								public void onClick(View v) {
									// TODO Auto-generated method stub
									dialog.dismiss();
									try {
										String url = getResources().getString(
												R.string.urlupdate);
										Intent intent = new Intent(
												Intent.ACTION_VIEW, Uri
														.parse(url));
										Log.d("logTag", url + ":update");
										startActivity(intent);
									} catch (Exception e) {

									}
								}
							});
					buttonDesau.setOnClickListener(new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							dialog.dismiss();
							if (checkshow.isChecked()) {

								SharedPreferences share = getSharedPreferences(
										"sharefilmllk", MODE_PRIVATE);
								SharedPreferences.Editor editor = share.edit();
								editor = share.edit();
								editor.putBoolean("checkbox", true);
								editor.commit();
							}
						}
					});
				}
				if (require.equals("require") && update) {
					final Dialog dialog = new CustomDialogClass(
							MainActivity.this)
							.createCustomDialog(
									R.layout.dialog_connect_main,
									MainActivity.this,
									getResources().getString(R.string.infor),
									getResources().getString(R.string.new_update_force),
									false);

					dialog.show();
					Button buttonOk = (Button) dialog
							.findViewById(R.id.buttonOk);
					buttonOk.setOnClickListener(new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							dialog.dismiss();
							SharedPreferences share = getSharedPreferences(
									"sharefilmllk", MODE_PRIVATE);
							SharedPreferences.Editor editor = share.edit();
							editor.putBoolean("require", true);
							editor.commit();
							String url = getResources().getString(
									R.string.urlupdate);
							Intent intent = new Intent(Intent.ACTION_VIEW, Uri
									.parse(url));
							startActivity(intent);
						}
					});
				} 
				if (!update || (update && require.equals("notrequire"))) {
//					new loadvideo(adapter, false, urlllk, films, footer, nodata, count)
//							.execute();
					//new LoadVideoYoutube(Config.appCat).execute();
					page = 1;
					ID = Config.mostlatest;
					asynSearch = new AsynSearch(ID);
					asynSearch.execute();
				}
			} catch (Exception e) {

			}
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			nodata.setVisibility(View.INVISIBLE);
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			// TODO Auto-generated method stub
			boolean result = false;
			try {
				HttpParams httpParameters = new BasicHttpParams();
				// Set the timeout in milliseconds until a connection is
				// established.
				int timeoutConnection = 3000;
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				// Set the default socket timeout (SO_TIMEOUT)
				// in milliseconds which is the timeout for waiting for data.
				int timeoutSocket = 3000;
				HttpConnectionParams
						.setSoTimeout(httpParameters, timeoutSocket);

				HttpPost httppost = new HttpPost(urljson);
				System.out.println("URL JSOM ALF " + urljson);
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
						2);
				nameValuePairs.add(new BasicNameValuePair("command", command));
				nameValuePairs.add(new BasicNameValuePair("appname", appname));

				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpResponse response = httpclient.execute(httppost);
				StatusLine status = response.getStatusLine();
				if (status.getStatusCode() == HttpStatus.SC_OK) {

					InputStream is = response.getEntity().getContent();

					BufferedReader reader = new BufferedReader( 
							new InputStreamReader(is, "utf-8"));
					String line = null;
					String data = "";
					while ((line = reader.readLine()) != null) {
						data += line;
					}
					is.close();
					HashMap<String, String> temp;
					// add to josnobject
					JSONObject jObj = new JSONObject(data);
					JSONArray jItems = jObj.getJSONArray(TAG_RESULT);
					temp = new HashMap<String, String>();
					JSONObject vs = jItems.getJSONObject(0);
					String version = vs.getString(TAG_VERSION);
					String require = vs.getString(TAG_REQUIRE);

					temp.put("version", version);
					temp.put("require", require);

					versions.add(temp);

					result = true;
				}
			} catch (Exception e) {
				// TODO: handle exception
				result = false;
			}
			return result;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
//			if (result) {
				checkvs(versions);
//			} else {
//				nodata.setVisibility(View.VISIBLE);
//			}
		}

	}
	
	public class LoadVideoYoutube extends AsyncTask<Void, Void, String>{
		String nameVideo;
		
		public LoadVideoYoutube(String nameVideo){
			this.nameVideo = nameVideo;
		}
		
		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			return JsonParse.getInstance().getVideo(MainActivity.this.getApplicationContext(), nameVideo);
		} 
		@Override 
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			try {
				if(result.equalsIgnoreCase("busy")){
					AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
					alert.setTitle("");
					alert.setMessage(getResources().getString(R.string.notresponse));
					alert.setNeutralButton(getResources().getString(R.string.notresponse_tryagain), new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Config.isShowingServerBusy = false;
							handler.post(new Runnable() {
						 		
								@Override
								public void run() {
									new LoadVideoYoutube(Config.appCat).execute();
								}
							});
						}
					});
					alert.setPositiveButton(getResources().getString(R.string.notresponse_existapp), new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							finish();
						}
					});
					if(!Config.isShowingServerBusy && Utility.checkNet(getApplicationContext())){
						alert.show();
						Config.isShowingServerBusy = true;
					}
				}else{
				JSONObject json = new JSONObject(result);
				if(!json.getString("result").equalsIgnoreCase("norow")){
					JSONArray arr = json.getJSONArray("result");
					for(int i=0;i<arr.length();i++){
						JSONObject obj = arr.getJSONObject(i);
						String name = obj.getString("VideoID");
						int id = Integer.parseInt(obj.getString("ID"));
						VideoID cat = new VideoID(id, name);
						video.add(cat);
					}
					 
					urlllk = "https://gdata.youtube.com/feeds/api/playlists/"
							+ video.get(n).getVideoID() + "?alt=jsonc&v=2&start-index=1"
							+ "&max-results=" + max_count_video;
					//loadvideo l = new loadvideo(adapter, false, urlllk, films, footer, nodata, count);
					//l.loadvideo(MainActivity.this,"json");
				}
				}
			} catch (JSONException e) {
				Log.e("error",e.getMessage());
				e.printStackTrace();
			}
			
		}
	}
	@Override
	public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getSupportMenuInflater().inflate(R.menu.main, menu);
		
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case android.R.id.home:
			menu.toggle();
			return true;
		case R.id.moreapp:
			String url = getResources().getString(R.string.urlmoreapp);
			Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
			startActivity(intent);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	private static boolean loading = false;
	public class EndlessScrollListener implements OnScrollListener {
		private int visibleThreshold;
		private int previousTotal;
		
		public EndlessScrollListener() {
			visibleThreshold = 1;
			previousTotal = 0;
		}
 
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			if (loading) {
				if (totalItemCount > previousTotal) {
					loading = false;
					previousTotal = totalItemCount;			
				}
			}  
			if (!loading	&& (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
				loading = true;
				if(asynSearch!=null && adapter!=null && adapter.getCount()>0 && asynSearch.getStatus()==AsyncTask.Status.FINISHED){
					if(Utility.checkNet(getApplicationContext())){
					asynSearch = new AsynSearch(ID);
					asynSearch.execute();
					}
				}
			}			
		}

		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub

		}

	}

	boolean hasNetwork = false;

	public void checkNet() {
		if (NetworkUtil.getInstance(getApplicationContext()).isConnect()) {
			hasNetwork = true;
			Log.d("logTag", "co máº¡ng");
			// showMSG("No network!");

		} else {
			hasNetwork = false;
			Log.d("logTag", "no máº¡ng");
			// showMSG("No network!");
		}
	}

	waitingOpenNetwork wait;
	boolean run = true;

	class waitingOpenNetwork implements Runnable {
		int timewaiting = 300;
		private boolean killMe = false;

		@Override
		public void run() {
			// TODO Auto-generated method stub
			checkNet();
			if (hasNetwork && run) {
				run = false;
				handler.removeCallbacksAndMessages(null);
				killRunnable();
				checkversion();
			}
			// Toast.makeText(getApplicationContext(), "waiting",
			// Toast.LENGTH_SHORT).show();
			handler.postDelayed(wait, timewaiting);
			if (killMe)
				return;

		}

		private void killRunnable() {
			killMe = true;
		}
	}

	public void showMSG() {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				final Dialog dialog = new CustomDialogClass(MainActivity.this)
						.createCustomDialog(R.layout.dialog_main,
								MainActivity.this, "Hi!",
								"KhÃ´ng cÃ³ káº¿t ná»‘i máº¡ng!", false);

				dialog.show();
				Log.d("logTag", "noo máº¡ng");
				Button btnCancel = (Button) dialog
						.findViewById(R.id.buttonCancel);
				Button btnSetting = (Button) dialog
						.findViewById(R.id.buttonSettings);
				btnSetting.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						dialog.dismiss();
						try {
							handler = new Handler();
							wait = new waitingOpenNetwork();
							handler.postDelayed(wait, 300);

							Intent i = new Intent(
									Settings.ACTION_WIRELESS_SETTINGS);
							startActivity(i);
						} catch (Exception e) {
							Toast.makeText(getApplicationContext(),
									e.getMessage(), Toast.LENGTH_SHORT).show();
						}
					}
				});
				btnCancel.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						dialog.dismiss();
						try {
							wait.killRunnable();
						} catch (Exception e) {

						}

					}
				});
			}
		});

	}

	Dialog dialog;

	public void showExit() {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				dialog = new CustomDialogClass(MainActivity.this)
						.createCustomDialogExit(R.layout.dialog_exit,
								MainActivity.this, false);

				dialog.show();
				Button btnMoreApp = (Button) dialog
						.findViewById(R.id.buttonMoreApp);
				Button btnExit = (Button) dialog.findViewById(R.id.buttonExit);
				btnMoreApp.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						dialog.dismiss();
						try {
							String url = getResources().getString(
									R.string.urlmoreapp);
							Intent intent = new Intent(Intent.ACTION_VIEW, Uri
									.parse(url));
							startActivity(intent);
						} catch (Exception e) {

						}
					}
				});
				btnExit.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Log.d("json","asd");
					//	startAppAd.showAd(); 
					  //  startAppAd.loadAd();
						dialog.dismiss();
						
						try {
							System.exit(0);
						} catch (Exception e) {

						}

					}
				});
			}
		});

	}
	@Override 
	  public void onPause() { 
	      super.onPause(); 
	    //  uiHelper.onPause();
	  //.onPause(); 
	  } 
	@Override
	public void onDestroy() {
	    super.onDestroy();
	 //   uiHelper.onDestroy();
	}
	public void showexit() {
		dialogexit = new Dialog(MainActivity.this);
		dialogexit = new Dialog(MainActivity.this,
				android.R.style.Theme_Translucent);
		dialogexit.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialogexit.setCancelable(true);
		dialogexit.setContentView(R.layout.dialog_exit);
		dialogexit.show();
		Button btnMoreApp = (Button) dialogexit
				.findViewById(R.id.buttonMoreApp);
		Button btnExit = (Button) dialogexit.findViewById(R.id.buttonExit);
		Button btngopy = (Button) dialogexit.findViewById(R.id.buttongopy);
		btnMoreApp.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialogexit.dismiss();
				try {
					String url = getResources().getString(R.string.urlmoreapp);
					Intent intent = new Intent(Intent.ACTION_VIEW, Uri
							.parse(url));
					startActivity(intent);
				} catch (Exception e) {

				}
			}
		});
		btnExit.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialogexit.dismiss();
			//	startAppAd.showAd(); 
			   //.loadAd();
			    Log.d("json","asaa");
			    finish();
				try {
					//System.exit(0);
				} catch (Exception e) {

				}

			}
		}); 
		btngopy.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialogexit.dismiss();
				String support = getResources().getString(R.string.supportemail);
				String body = "";
				Intent intent = new Intent(Intent.ACTION_VIEW);
				Uri data = Uri.parse("mailto:?subject=" + support + "&body="
						+ body + "&to="
						+ getResources().getString(R.string.support));

				intent.setData(data);
				startActivity(intent);
			}
		});
	}

	boolean se = false;
	Dialog dialogexit;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (!se) {
				se = true;
				showexit();
			} else {
				se = false;
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						dialogexit.dismiss();
					}
				});

			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onListitemClick(String item) {
		try {
			
			int view = Integer.parseInt(item);
			switch (view) {
			case 1:menu.toggle();
				Intent i = new Intent(getApplicationContext(), SearchActiviy.class);
				startActivity(i);
				break;
			case 2:menu.toggle();
				menu.toggle();
				page = 1;
				ID = Config.mostLiked;
				adapter.resetAdapter();
				asynSearch = new AsynSearch(ID);
				asynSearch.execute();
				break;
				
			case 3:menu.toggle();
				menu.toggle();
				page = 1;
				ID = Config.mostviewed; adapter.resetAdapter();
				asynSearch = new AsynSearch(ID);
				asynSearch.execute();
				break;
			case 4:menu.toggle();
				menu.toggle();
				page = 1;
				ID = Config.mostlatest; adapter.resetAdapter();
				asynSearch = new AsynSearch(ID);
				asynSearch.execute();
				break;
			default:
				break;
			}
		} catch (Exception e) {
			Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(item));
			startActivity(intent); 
		}
		
	}
	
	
	
	
	
	
	
	private int page = 1;
	private class AsynSearch extends AsyncTask<Void, Void, String>
	{
		ArrayList<Video> videos = new ArrayList<Video>();
		String menuID;
		
		
		public AsynSearch(String menuID){
			this.menuID = menuID;
		}
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();			
			if(adapter.getCount()==0){
				waiting.setVisibility(View.VISIBLE);
				footer.setVisibility(View.INVISIBLE);
			}
			else{
				waiting.setVisibility(View.INVISIBLE);
				footer.setVisibility(View.VISIBLE);
			}
		} 
		@Override
		protected String doInBackground(Void... params) {
			Log.d("log","asdasdasd");
			return JsonParse.getInstance().getVideo(getApplicationContext(), menuID, page++);
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			waiting.setVisibility(View.INVISIBLE);
			footer.setVisibility(View.INVISIBLE);	
			try {
				if(result.equalsIgnoreCase("busy")){ 
					page--;
					AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
					alert.setTitle("");
					alert.setMessage(getResources().getString(R.string.notresponse));
					alert.setNeutralButton(getResources().getString(R.string.notresponse_tryagain), new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							asynSearch = new AsynSearch(ID);
							asynSearch.execute();
							Config.isShowingServerBusy = false;
						}
					});
					alert.setPositiveButton(getResources().getString(R.string.notresponse_existapp), new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent i = new Intent(MainActivity.this, MainActivity.class);
							i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							i.putExtra("exit", "exit");
							startActivity(i);
						}
					});
					if(!Config.isShowingServerBusy && Utility.checkNet(getApplicationContext())){
						alert.show();
						Config.isShowingServerBusy = true;
					}
				}
				else{
					JSONObject json = new JSONObject(result);
					if(!json.getString(Config.result).equalsIgnoreCase(Config.norow)){
						JSONArray arr = json.getJSONArray(Config.result);
						for(int i=0;i<arr.length();i++){
							JSONObject obj = arr.getJSONObject(i);
							int id = Integer.parseInt(obj.getString(Video.KEY_ID));
							int videoID = Integer.parseInt(obj.getString(Video.KEY_videoID));
							String title = obj.getString(Video.KEY_title);
							String link = obj.getString(Video.KEY_link);
							String playerDefault = obj.getString(Video.KEY_playerDefault);
							String playerMobile = obj.getString(Video.KEY_playerMobile);
							String duration = obj.getString(Video.KEY_duration);
							String likes = obj.getString(Video.KEY_likes);
							String views = obj.getString(Video.KEY_Views);
							
							Video v = new Video(id, videoID, title, link, playerDefault, playerMobile, duration, likes, views);
							videos.add(v);
						}						
						adapter.updateVideo(videos);						
					}
					else if(adapter.getCount()==0){
						AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
						alert.setTitle("");
						alert.setMessage(getResources().getString(R.string.error));
						alert.setNeutralButton(getResources().getString(R.string.server_busy), new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								asynSearch = new AsynSearch(ID);
								asynSearch.execute();
							}
						});
						
						alert.show();  
					}
				}
			} catch (JSONException e) {
				Log.e("error",e.getMessage());
				e.printStackTrace();			 
			}
			loading = false;
		}
		
	}
	private class AsynLike extends AsyncTask<String, Void, String>
	{
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		} 
		@Override
		protected String doInBackground(String... params) {
			User u = new Database(getApplicationContext()).getUser();
			if(u!=null){
				return JsonParse.getInstance().IncreaLike(params[0],params[1],u.getUserId());
			}
			return null;
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			try {
				if(result.equalsIgnoreCase("busy")){
					AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
					alert.setTitle("");
					alert.setMessage(getResources().getString(R.string.notresponse));
					alert.setNeutralButton(getResources().getString(R.string.notresponse_tryagainlater), new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Config.isShowingServerBusy = false;
						}
					});
					alert.setPositiveButton(getResources().getString(R.string.notresponse_existapp), new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							finish();
						}
					});
					if(!Config.isShowingServerBusy && Utility.checkNet(getApplicationContext())){
						alert.show();
						Config.isShowingServerBusy = true;
					}
				}else{
				JSONObject json = new JSONObject(result);
				Video v = (Video) adapter.getItem(mSelectedRow);
				if(json.getString("result").equalsIgnoreCase("1")){
					
					if(v!=null)
					Toast.makeText(MainActivity.this, getResources().getString(R.string.alert_successful_like)+" "+v.getTitle(), Toast.LENGTH_LONG).show();		
				}
				else{
					if(v!=null)
						Toast.makeText(MainActivity.this, getResources().getString(R.string.alert_successful_like)+" "+v.getTitle(), Toast.LENGTH_LONG).show();		
				}
				}
			} catch (JSONException e) {
				Log.e("error",e.getMessage());
				e.printStackTrace();
			}
		}
	}
	@Override
	public void onClickItemVideo(int position, View v) {
		mSelectedRow = position; //set the selected row				
		mQuickAction.getActionItem(0).setTitle(((Video)adapter.getItem(position)).getLikes()+" "+getResources().getString(R.string.likes));
		mQuickAction.show(v);
		
	}
	ProgressDialog progress;
}


